package login

/*******************************************************************************
Copyright:cloud
Author:cloudapex@126.com
Version:1.0
Date:2020-06-12
Description: 登陆模块
*******************************************************************************/
import (
	"context"
	"permis/api/api"
	"permis/api/cache"
	"permis/model"

	gpb "gitee.com/cloudapex/protos/permis/pb"

	"gitee.com/cloudapex/ulern/util"
)

func GServer() *Server { return (&Server{}).Init() }

type Server struct {
	util.LogMe

	gpb.UnimplementedLoginServer
}

func (this *Server) Init() *Server {
	this.LogMe.Init("GRPC", func() string { return "login" })
	return this
}

// UIPermis 登陆时的权限数据
func (this *Server) MyPermis(ctx context.Context, req *gpb.MyPermisReq) (*gpb.MyPermisRes, error) {

	// 更换: 两个Id保持一致
	mUsr := model.User{Id: req.UId}
	if has, err := mUsr.Load(); !has || err != nil {
		if err != nil {
			return nil, api.DBError("", err)
		}
		return nil, api.DBError("用户不存在", err)
	}

	aIds, err := (&model.UserRole{UserId: mUsr.Id}).FindIds()
	if err != nil {
		return nil, api.DBError("", err)
	}
	rIds, err := (&model.UserGroupWithGroupRole{UserGroup: model.UserGroup{UserId: mUsr.Id}}).FindRoleIds()
	if err != nil {
		return nil, api.DBError("", err)
	}
	aIds = append(aIds, rIds...)

	// 拥有的权限
	mlist, plist := []model.MenuItem{}, []model.PowerItem{}
	if len(aIds) > 0 {
		mRPP := model.RolePowerWithPower{RolePower: model.RolePower{CInRIds: aIds}}

		mlist_, err := mRPP.FindMItems(model.EPower_Menu) // 拥有的菜单
		if err != nil {
			return nil, api.DBError("", err)
		}
		mlist = mlist_

		plist_, err := mRPP.FindPItems(model.EPower_Func) // 拥有的功能
		if err != nil {
			return nil, api.DBError("", err)
		}
		plist = plist_
	}

	util.Goroutine("HandUserRoles", func() { // 更新用户角色缓存
		if err := cache.HandUserRoles([]int64{mUsr.Id}, true); err != nil {
			this.Error("UIPermis.HandUserRoles err:%v", err)
		}
		if err := cache.HandUserDevce(mUsr.Id, req.UserAgent, req.UserDevice); err != nil {
			this.Error("UIPermis.HandUserDevce err:%v", err)
		}
	})
	res := gpb.MyPermisRes{}
	if err := util.Convert(&res.MList, mlist); err != nil {
		return nil, api.ConvertError("", err)
	}
	if err := util.Convert(&res.PList, plist); err != nil {
		return nil, api.ConvertError("", err)
	}
	return &res, nil
}
